﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class JwtHelper
    {
        static readonly string SecurityKey = "21218CCA77804D2BA1922C33E0151105";
        static readonly string Issuer = "Demo";
        static readonly string Audience = "wecityNb";
        static readonly int AccessExpiration = 60;

        public static string GetToken(string account)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.Name,account)
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurityKey));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(Issuer, Audience, claims,
                expires: DateTime.Now.AddMinutes(AccessExpiration),
                signingCredentials: credentials);
            return new JwtSecurityTokenHandler().WriteToken(jwtToken);
        }

        public static bool CheckToken(string encodedToken)
        {
            JwtSecurityToken token = new JwtSecurityToken(encodedToken);
            if (token.Claims == null)
            {
                return false;
            }
            Dictionary<string, string> claimVals = token.Claims.ToDictionary(x => x.Type, x => x.Value);
            if (claimVals["iss"] != Issuer || claimVals["aud"] != Audience)
            {
                return false;
            }
            DateTime expirationDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            expirationDate = expirationDate.AddMinutes(int.Parse(claimVals["exp"]));
            return expirationDate.ToLocalTime() >= DateTime.Now;
        }
    }
}
